<template>
  <el-dialog
      v-model="dialogShow"
      :before-close="close"
      :close-on-click-modal="false"
      :title="title"
      custom-class="mydialog"
      width="40%"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        size="small"
    >
      <el-form-item
          label="产品线名称"
          prop="productLineName"
          style="width: 100%"
      >
        <el-input
            v-model="form.productLineName"
            autocomplete="off"
            clearable
            placeholder="请输入产品线名称"
        />
      </el-form-item>

      <el-form-item
          label="负责部门"
          prop="deptId"
          style="width: 100%"
      >
        <el-cascader
            ref="cascader"
            v-model="form.deptId"
            :options="dep"
            :popper-append-to-body="false"
            :props="props1"
            :show-all-levels="false"
            placeholder="请选择负责部门"
            style="width: 100%"
            @change="change"
        />
      </el-form-item>

      <el-form-item
          label="负责职员"
          prop="userIds"
          style="width: 100%"
      >
        <el-select
            v-model="form.userIds"
            multiple
            placeholder="请选择负责职员"
            style="width: 100%"
            @change="userChange"
        >
          <el-option
              v-for="item in user"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
            class="border-btn"
            size="small"
            @click="close"
        >取消
        </el-button>
        <el-button
            class="main-btn"
            size="small"
            type="primary"
            @click="confirm"
        >保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import area from '@/utils/area.js'
import {defineComponent, getCurrentInstance, inject, onMounted, reactive, ref, toRefs,} from 'vue'

export default defineComponent({
  name: 'CreateOrChange',
  emits:['success'],
  props: {
    title: {
      type: String,
      default: '',
    },
    // form: {
    //   type: Object,
    //   default: () => {},
    // },
  },
  setup(props, context) {
    const api = inject('api')
    const citys = area
    const currentInstance = getCurrentInstance()
    const props1 = reactive({
      checkStrictly: true,
      expandTrigger: 'hover',
      label: 'deptName',
      value: 'id',
    })
    var dialogShow = ref(false)
    var formRef = ref(null)
    var data = reactive({
      dep: [],
      user: [],
    })
    const open = (val) => {
      if (val) {
        form.id = val.id
        form.productLineName = val.productLineName
        form.deptId = val.deptId
        form.userIds = val.userIds
        getUserList()
        if (val.deptIds) {
          form.deptIds = JSON.parse(val.deptIds)
          if (form.deptIds.length) {
            getUser(form.deptIds)
          }
        }
      } else {
        form.id = 0
        form.deptId = 0
        data.user = []
        form.userIds = []
        form.deptIds = []
        form.productLineName = ''
      }
      dialogShow.value = true
    }
    const parentAreas = ref([])
    var form = reactive({
      id: 0,
      productLineName: '',
      deptId: '',
      deptIds: [],
      userIds: [],
    })
    const validateName = async (rule, value, callback) => {
      if (value === '') {
        callback('请输入产品线名称')
      } else {
        const name = await validateVEName(value)
        if (name) {
          callback(new Error('产品线名称已存在'))
        } else {
          callback()
        }
      }
    }
    const validateVEName = async (val) => {
      const pam = {
        table: 'sys_product_line',
        column: 'product_line_name',
        column_data: val,
        id: form.id ? form.id : 0,
      }
      const booleName = ref(false)
      const res = await api.common.COMMON_CHECK_UNIQUE(pam)
      if (res.code === 0) {
        if (res.data.exist !== '0') {
          booleName.value = true
        }
      }
      return booleName.value
    }
    var rules = reactive({
      productLineName: [
        {required: true, validator: validateName, trigger: 'blur'},
      ],
      deptId: [
        {required: true, message: '请选择负责部门', trigger: 'change'},
      ],
      userIds: [
        {required: true, message: '清选择负责职员', trigger: 'change'},
      ],
    })
    const getUserList = () => {
      api.system.SYSDEPT_USER(form.deptId).then((res) => {
        if (!res.code) {
          data.user = res.data
        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        }
      })
    }

    const close = () => {
      dialogShow.value = false
      form.productLineName = ''

      formRef.value.resetFields()
      formRef.value.clearValidate()
    }
    const confirm = () => {
      if (props.title == '添加产品线') {
        formRef.value.validate((valid) => {
          if (valid) {
            const data = {
              productLineName: form.productLineName,
            }
            console.log(form)
            form.deptIds = JSON.stringify(form.deptIds)
            api.system.PRODUCTLINE_CREATE(form).then((res) => {
              if (res.code == 0) {
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '添加成功',
                })
                context.emit('success')
              } else {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: res.msg,
                })
              }
              close()
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        formRef.value.validate((valid) => {
          if (valid) {
            const data = {
              id: form.id,
              productLineName: form.productLineName,
            }

            const a = JSON.parse(JSON.stringify(form))
            a.deptIds = JSON.stringify(a.deptIds)
            console.log(a.userIds)
            console.log(a)
            api.system.PRODUCTLINE_UPDATE(a).then((res) => {
              if (!res.code) {
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '编辑成功',
                })
                context.emit('success')
              } else {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: res.msg,
                })
              }
            })
            close()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    }
    onMounted(() => {
      api.system.SYSDEPT_TREE().then((res) => {
        if (!res.code && res.data) {
          dealDep(res.data)
          data.dep = res.data
        } else {
        }
      })
    })

    const dealDep = (list) => {
      if (list && list.length){
        list.forEach((item) => {
          if (item.children) {
            dealDep(item.children)
          }
          if (
                  (!item.users || !item.users.length) &&
                  (!item.children || !item.children.length)
          ) {
            item.disabled = true
          }
        })
      }
    }

    const getUser = (arr) => {
      let dep = {}
      let list = JSON.parse(JSON.stringify(data.dep))
      if (arr && arr.length){
        arr.forEach((a) => {
          for (let i = 0; i < list.length; i++) {
            if (list[i].id == a) {
              dep = list[i]
              if (dep.children) {
                list = dep.children
              }
              break
            }
          }
        })
      }

      data.user = dep.users
    }

    const change = (val) => {
      console.log(val)
      form.deptId = val[val.length - 1]
      form.userIds = []
      // getUser(val)
      getUserList()
    }

    const userChange = (val) => {
      console.log(val)
      console.log(form.userIds)
    }

    return {
      ...toRefs(data),
      api,
      dialogShow,
      open,
      form,
      parentAreas,
      citys,
      props1,
      close,
      confirm,
      rules,
      formRef,
      currentInstance,
      change,
      userChange,
    }
  },
})
</script>
